package com.github.zy.rpc.service.handler;

import com.github.zy.rpc.constants.Profile;
import com.github.zy.rpc.session.Session;
import com.github.zy.rpc.session.SessionHelper;
import com.github.zy.rpc.session.SessionManager;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @version 1.0 created by zy on 2020/4/28 14:19
 */
@Slf4j
@Component
public class DefaultServerSender implements ServerSender {
    @Autowired
    private SessionManager sessionManager;

    @Override
    public void sendToClient(String moduleId, String urlMapping, Object msg) {
        Collection<Session> sessions = sessionManager.findByModuleId(moduleId);
        sessions.forEach(session -> {
            Channel channel = session.getChannel();
            channel.writeAndFlush(buildRequestMessagePacket(msg, moduleId, urlMapping));
        });
    }

    @Override
    public void sendToClient(String moduleId, String urlMapping, Profile profile, Object msg) {
        Collection<Session> sessions = sessionManager.findByModuleId(moduleId);
        sessions.forEach(session -> {
            Profile sessionProfile = session.getProfile();
            if (sessionProfile.getType().equals(profile.getType())) {
                Channel channel = session.getChannel();
                channel.writeAndFlush(buildRequestMessagePacket(msg, moduleId, urlMapping));
            }
        });
    }

    @Override
    public void sendToClient(String moduleId, String urlMapping, String ip, int port, Object msg) {
        Collection<Session> sessions = sessionManager.findByModuleId(moduleId);
        sessions.forEach(session -> {
            if (session.getId().equals(SessionHelper.getSessionId(ip, port))) {
                Channel channel = session.getChannel();
                channel.writeAndFlush(buildRequestMessagePacket(msg, moduleId, urlMapping));
            }
        });
    }

    @Override
    public void sendToClient(String moduleId, String urlMapping, Profile profile, String ip, int port, Object msg) {
        Collection<Session> sessions = sessionManager.findByModuleId(moduleId);
        sessions.forEach(session -> {
            Profile sessionProfile = session.getProfile();
            if (session.getId().equals(SessionHelper.getSessionId(ip, port)) && sessionProfile.getType().equals(profile.getType())) {
                Channel channel = session.getChannel();
                channel.writeAndFlush(buildRequestMessagePacket(msg, moduleId, urlMapping));
            }
        });
    }

    @Override
    public void sendToClient(Session session) {
        //session.getChannel().
    }
}
